package net.diaowen.dwsurvey.controller;

import net.diaowen.common.base.entity.Org;
import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.plugs.mapper.ObjectMapper;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.common.utils.ExportReportThread;
import net.diaowen.common.utils.SendNotifyThread;
import net.diaowen.common.utils.weixin.WeixinBind;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.entity.SurveyGroup;
import net.diaowen.dwsurvey.entity.UserGroupInfo;
import net.diaowen.dwsurvey.service.OrgManager;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;
import net.diaowen.dwsurvey.service.SurveyGroupManager;
import net.diaowen.dwsurvey.service.impl.UserGroupInfoManagerImpI;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by keyuan on 17/7/31.
 */
@Controller
@RequestMapping("/design/my-survey")
public class MySurveyController {

    @Autowired
    private SurveyDirectoryManager surveyDirectoryManager;
    @Autowired
    private SurveyGroupManager surveyGroupManager;   
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private OrgManager orgManager;

    @Autowired
    private UserGroupInfoManagerImpI userGroupInfo;

    @RequestMapping("/list.do")
    public ModelAndView list(HttpServletRequest request,SurveyDirectory entity,Page<SurveyDirectory> page) throws Exception {
        String surveyState = request.getParameter("surveyState");
        if(surveyState==null||"".equals(surveyState)){
            entity.setSurveyState(null);
        }
        page=surveyDirectoryManager.findByUser(page,entity);
        ModelAndView modelAndView = new ModelAndView();
        List<Org>orgList=new ArrayList<Org>();
        User user = accountManager.getCurUser();
        if(user!=null){
            if (user.getSystemRole() == 8) {
                orgList=orgManager.findList();
            }
        }
        modelAndView.addObject("orgs",orgList);
        modelAndView.addObject("surveyName",entity.getSurveyName());
        modelAndView.addObject("surveyState",surveyState);
        modelAndView.setViewName("/diaowen-design/list");
        modelAndView.addObject("page",page);

//        User tempUser = new User();
//        tempUser.setId("2c9286ca7216eac0017225e062d301fd");
//        tempUser.setOrgId("6");
//        tempUser.setStudentId("41601432");
//
//
//        surveyDirectoryManager.findByUser(tempUser);

        return modelAndView;
    }

    @RequestMapping("/delete.do")
    @ResponseBody
    public String delete(String id) throws Exception {
        String result="false";
        try{
            User user = accountManager.getCurUser();
            if(user!=null){
                String userId=user.getId();
	    		//如果是超级管理员，则有权查看所有
	    		SurveyDirectory surveyDirectory = null;
	    		if (user.getSystemRole() == 8) {
	    			surveyDirectory = surveyDirectoryManager.get(id);
	    		} else {
	    			surveyDirectory = surveyDirectoryManager.getSurveyByUser(id, userId);		    			
	    		}
                if(surveyDirectory!=null){
                    surveyDirectoryManager.delete(id);
					//把下挂的小组信息也清空干净
					surveyGroupManager.removeBySurveyId(id);
                    result="true";
                }
            }
        }catch (Exception e) {
            result="false";
        }
        return result;
    }


    @RequestMapping("/notify.do")
    @ResponseBody
    public String notify(String id) throws Exception {
        String result="false";
        try{
            User user = accountManager.getCurUser();
            System.out.println("user.getName() = " + user.getName());
            System.out.println("user.getSystemRole() = " + user.getSystemRole());
            if(user!=null){
                String userId=user.getId();
                //如果是超级管理员，则有权查看所有
                SurveyDirectory surveyDirectory = null;
                if (user.getSystemRole() == 8) {
                    surveyDirectory = surveyDirectoryManager.get(id);
                } else {
                    surveyDirectory = surveyDirectoryManager.getSurveyByUser(id, userId);
                }
                if(surveyDirectory!=null){

                    //查询问卷下面的小组信息
                    List<SurveyGroup> groupList=  surveyGroupManager.findListBySurveyId(id);
                    if(groupList!=null)
                    {
                        //按小组发通知，查询所有已绑定微信用户名单，只有已绑定的用户才能通知,为防止意外，
                        // 目前仅支持对按小组发布用户发布通知
                        for(int i=0;i<groupList.size();i++) {
                            SurveyGroup tempGroup  = groupList.get(i);
                           // 每个小组下绑定者的微信id
                            List<Object[]> temp=surveyGroupManager.getGroupWinUser(tempGroup.getGroupId());
                            for (int j = 0; j < temp.size(); j++) {
                                String wix = String.valueOf(temp.get(j));
                                SendNotifyThread sendNotifyThread = new SendNotifyThread();
                                sendNotifyThread.setTouser(wix);
                                sendNotifyThread.setSurveyGroupManager(surveyGroupManager);
                                sendNotifyThread.setUserName(user.getName());
                                sendNotifyThread.setServeyName(surveyDirectory.getSurveyName());
                                sendNotifyThread.start();
                            }
                        }

                    }

                    result="true";
                }
            }
        }catch (Exception e) {
            result="false";
        }
        return result;
    }

    @RequestMapping("/surveyState.do")
    //问卷壮态设置
    @ResponseBody
    public String surveyState(String id,Integer surveyState) throws Exception{
        String result="";
        try{
            User user= accountManager.getCurUser();
            if(user!=null){
                String userId=user.getId();
	    		//如果是超级管理员，则有权查看所有
	    		SurveyDirectory surveyDirectory = null;
	    		if (user.getSystemRole() == 8) {
	    			surveyDirectory = surveyDirectoryManager.get(id);
	    		} else {
	    			surveyDirectory = surveyDirectoryManager.getSurveyByUser(id, userId);	    			
	    		}
                if(surveyDirectory!=null){
                    surveyDirectory.setSurveyState(surveyState);
                    surveyDirectoryManager.save(surveyDirectory);
                }
            }
            result="true";
        }catch(Exception e){
            e.printStackTrace();
            result="error";
        }
        return result;
    }

    @RequestMapping("/attrs.do")
    @ResponseBody
    public SurveyDirectory attrs(String id) throws Exception {
        try{
            SurveyDirectory survey=surveyDirectoryManager.findUniqueBy(id);
//            JsonConfig cfg = new JsonConfig();
//            cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});
//            JSONObject jsonObject=JSONObject.fromObject(survey,cfg);
//            return jsonObject.toString();
            return survey;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
